package com.datn.activity;

import java.util.ArrayList;

import com.datn.DataAccess.FavouriteDatabaseAdapter;
import com.datn.DataAccess.InstructionDatabaseAdapter;
import com.datn.DataAccess.ListPlaceAdapter;
import com.datn.beans.FavouriteBean;
import com.datn.beans.UserBean;
import com.datn.utils.AlertCustom;
import com.datn.utils.BitmapUtils;
import com.datn.utils.DistanceUtils;
import com.datn.utils.PreferenceUtils;
import com.datn.utils.ScreenSizeUtils;

import com.datn.utils.GPSUtils;
import com.datn.utils.places.DirectionObject;
import com.datn.utils.places.JsonAnyPlace;
import com.datn.utils.places.JsonDirection;
import com.datn.utils.places.JsonPlace;
import com.datn.utils.places.Place;
import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListPlaceActivity extends Activity implements OnItemClickListener{

	Intent intent;
	ArrayList<Place> array;
	ListPlaceAdapter arrayAdapter;
	ListView lst;
	String stCategory;
	GeoPoint currentLocation;
	Context mContext;
	
	public void getValueFromPreference(){
		
		stCategory = PreferenceUtils.getCategory();
		Log.v("Category", stCategory);
	}
	
	public void writeValueToPreference(Place place, String stCategory){
		PreferenceUtils.setPlaceDetails(place);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		PreferenceUtils.getInstance(this);
		setContentView(R.layout.list_item_place);
		mContext=this;
		
		//Get value user selected as: ATM, Bank ...
		getValueFromPreference();		
		array=new ArrayList<Place>();
		arrayAdapter=new ListPlaceAdapter(mContext, R.layout.item_place, array);			
		lst=(ListView) findViewById(R.id.lvListItemPlace);
		lst.setAdapter(arrayAdapter);		
		
		
		currentLocation= PreferenceUtils.getCurrentLocation();
		showListPlace(stCategory, currentLocation);
		arrayAdapter.notifyDataSetChanged();
			
		lst.setOnItemClickListener(this);
	}
	
	
	
	
	
	//Process When User select the place
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int i, long arg3) {
		// TODO Auto-generated method stub
		FavouriteDatabaseAdapter adapter=null;
		FavouriteDatabaseAdapter adapterNew = null;
		try{
		intent=new Intent(this,DetailsPlaceActivity.class);			
		writeValueToPreference(array.get(i), stCategory);
		PreferenceUtils.setModeOnlinẹ̣(true);
		if (UserBean.isLogin){
			adapter =new FavouriteDatabaseAdapter(this);
			adapter.open();
			Place place = array.get(i);
			FavouriteBean bean = new FavouriteBean();
				bean.setAddress(place.getAddressLine());
				bean.setNameplace(place.getName());
				bean.setLatitude(place.getLatitude());
				bean.setLongitude(place.getLongtitude());
				bean.setUrl(place.getActualurl());
				bean.setPhonenumber(place.getPhonenumber());
				bean.setUsername(UserBean.username);
				GeoPoint endPosition = new GeoPoint((int)(place.getLatitude()*1E6), (int)(place.getLongtitude()*1E6));
				if (endPosition!=null){
					ScreenSizeUtils size=new ScreenSizeUtils(mContext);
					size.setSizePercentFollowDevice(80);
					int width = size.getWidth();
					int height = size.getWidth();
					Bitmap bitmap = BitmapUtils.getDirectionStaticImageGoogleMap(currentLocation, endPosition, width, height);
				if (bitmap!=null)
					{
						bean.setImage(bitmap);
					}
				}
			int resultCreate = adapter.updateRecentPlace(bean);
			adapter.close();
			
			if (bean!=null){
				if (resultCreate!=-1){
					adapterNew = new FavouriteDatabaseAdapter(this);
					adapterNew.open();
						int place_id = adapterNew.getPlaceIdFromLatLngRecent(String.valueOf(bean.getLatitude()), String.valueOf(bean.getLongitude()));
						Log.v("PlaceIDDDDDDDDDDDD", String.valueOf(place_id));						
						GeoPoint startLocation = PreferenceUtils.getCurrentLocation();
						GeoPoint endLocation = new GeoPoint((int)(array.get(i).getLatitude()*1E6), (int)(array.get(i).getLongtitude()*1E6));
						JsonDirection jsonDirection=new JsonDirection(this, startLocation, endLocation);
						DirectionObject direction = jsonDirection.getDirectionFromJSON();
						ArrayList<String> allInstruction = direction.getInstructions();
					adapterNew.close();
					
					InstructionDatabaseAdapter adapterInstruction = new InstructionDatabaseAdapter(this);
					adapterInstruction.open();
						adapterInstruction.createInstruction(String.valueOf(place_id), allInstruction);
					adapterInstruction.close();
				}
			}
			
		}
		startActivity(intent);
		finish();
		}
		catch (Exception e) {
			// TODO: handle exception
			AlertCustom.showAlert(this, "ERROR", "Cannot get details place:\n"+e.getMessage());
		} finally{
			try {
				adapter.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
			
			try {
				adapterNew.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
			
			
		}
	}
	
	
	
	public void showListPlace(final String stCategory, final GeoPoint currentLocation){
		new AsyncTask<String, Void, ArrayList<Place>>() 
		{
			private ProgressDialog mProgressDialog;
			JsonPlace json_Place;
			@Override
			protected void onPreExecute() 
			{
				array=new ArrayList<Place>();
				json_Place=new JsonPlace(mContext);
				mProgressDialog = new ProgressDialog(mContext);
				mProgressDialog.setMessage("Please Wait...");
				mProgressDialog.setCancelable(false);
				mProgressDialog.setIndeterminate(true);
				mProgressDialog.show();
			};

			@Override
			protected ArrayList<Place> doInBackground(String... args) {
				// TODO Auto-generated method stub
				try {
					if (PreferenceUtils.isSearchTypeAnyAddress()){
						JsonAnyPlace jsonAnyPlace = new JsonAnyPlace(mContext);
						String stValue = PreferenceUtils.getSearchTypeValue();
						if (stValue==null) stValue = "";
						array.addAll((ArrayList<Place>)jsonAnyPlace.getListAnyAddress(stValue));
					}
					else {
						array.addAll((ArrayList<Place>)json_Place.getListAdressByType(stCategory, currentLocation));
					}
					
					
				} catch (Exception e) {
					// TODO Auto-generated catch block					
				}
				return array;
			}

			@Override
			protected void onPostExecute(ArrayList<Place> array) 
			{
				if (mProgressDialog.isShowing()) 
				{
					mProgressDialog.dismiss();
				}
				if (array != null) 
				{
					arrayAdapter=new ListPlaceAdapter(mContext, R.layout.item_place, array);			
					lst=(ListView) findViewById(R.id.lvListItemPlace);
					lst.setAdapter(arrayAdapter);
					arrayAdapter.notifyDataSetChanged();
				} else 
				{
					AlertCustom.showAlert(mContext, "Error", "Cannot receive list place.");
				}

			};
		}.execute("...");
	}
	
	
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if (keyCode==KeyEvent.KEYCODE_BACK){
			Intent intent=new Intent(this, NearLocationActivity.class);
			startActivity(intent);
			finish();
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	
	
	
	
}
